package com.study.spring.filters;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Collections;

/**
 * @author zhangjunfei
 * @date 2024/5/11 10:23
 */
@Configuration
public class FilterConf implements WebMvcConfigurer {

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);    // 允许cookies跨域
        corsConfiguration.setMaxAge(1800L);             // 预检请求的缓存时间（秒），即在这个时间段里，对于相同的跨域请求不会再预检了
        corsConfiguration.addAllowedOrigin("*");        // 允许任何“源”(域名)使用
        corsConfiguration.addAllowedHeader("*");        // 允许任何请求头
        corsConfiguration.addAllowedMethod("*");
        // 允许任何方法（get、post等）
        source.registerCorsConfiguration("/**", corsConfiguration);     // 处理所有请求的跨域配置

        FilterRegistrationBean registrationBean = new FilterRegistrationBean(new CorsFilter(source));   // 注册自定义过滤器
        registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);  // 优先级最高
        registrationBean.setUrlPatterns(Collections.singletonList("/*"));
        return registrationBean;
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {

        // registry.addMapping("/**")
        //         .allowedMethods("*")
        //         .allowedHeaders("*")
        //         .allowedOrigins("*")
        //         .allowCredentials(true)
        //         .maxAge(3600L);
    }
}
